package com.qifan.energy.activity;

import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.PermissionUtils;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.qifan.energy.base.BaseActivity;
import com.qifan.energy.bean.result.OSSCallbackResult;
import com.qifan.energy.bean.vo.UpdateInfoVO;
import com.qifan.energy.mvp.callback.ICallBack;
import com.qifan.energy.mvp.callback.IEventCallback;
import com.qifan.energy.mvp.callback.IEventIndexCallback;
import com.qifan.energy.mvp.callback.IPhotoOptionCallback;
import com.qifan.energy.R;
import com.qifan.energy.bean.result.MemberInfo;
import com.qifan.energy.bean.result.OSSPolicyResult;
import com.qifan.energy.global.GlideApp;
import com.qifan.energy.global.Keys;
import com.qifan.energy.global.Values;
import com.qifan.energy.http.net.NetUtils;
import com.qifan.energy.http.response.MyObserver;
import com.qifan.energy.util.ActivityStackUtil;
import com.qifan.energy.util.IntentUtils;
import com.qifan.energy.util.SharedPreferencesUtil;
import com.qifan.energy.util.ToastUtils;
import com.qifan.energy.util.UIUtils;
import com.qifan.energy.util.oss.OSSNetUtils;
import com.qifan.energy.widget.dialog.GenderBottomDialog;
import com.qifan.energy.widget.dialog.LoadingUtils;
import com.qifan.energy.widget.dialog.NormalCenterDialog;
import com.qifan.energy.widget.dialog.SheetBottomDialog;
import com.orhanobut.logger.Logger;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class UserInfoActivity extends BaseActivity {

    @BindView(R.id.avatar_iv)
    CircleImageView avatarIv;
    @BindView(R.id.nick_tv)
    TextView nickTv;
    @BindView(R.id.gender_tv)
    TextView genderTv;
    @BindView(R.id.mobile_tv)
    TextView mobileTv;
    @BindView(R.id.done_btn)
    TextView doneBtn;
    /* 性别0未知  1男 2女 */
    private int gender = 0;

    /*@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView();
    }*/

    @Override
    protected int getLayoutId() {
        return R.layout.activity_user_info;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        /* 更改状态栏 */
        changeStatusTransparentFontBlack();

        /* 控件赋值 */
        /* 获取本地用户信息 */
        MemberInfo result = SharedPreferencesUtil.getData(Keys.USER_INFO_MEMBER_KEY,new MemberInfo());
        String phone = result.getPhone();
        String nickname = result.getNickname();
        Integer gender = result.getGender();
        if (!TextUtils.isEmpty(phone)){
            mobileTv.setText(phone);
        }
        if (!TextUtils.isEmpty(nickname)){
            nickTv.setText(nickname);
        }
        if (null == gender){
            genderTv.setText("未填写");
            this.gender = 0;
        } else {
            String genderStr = (gender == 1 ? "男" : "女");
            genderTv.setText(genderStr);
            this.gender = gender;
        }

        if (!TextUtils.isEmpty(result.getIcon())){
            GlideApp.with(this)
                    .load(result.getIcon())
                    .placeholder(R.mipmap.icon_default_avatar)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .error(R.mipmap.icon_default_avatar)
                    .circleCrop()
                    .into(avatarIv);
        }
    }

    @Override
    protected void initData() {

    }

    /* 头像 */
    @OnClick(R.id.avatar_ll)
    void onAvatarLlClicked(){
        //ToastUtils.showShort("头像");
        SheetBottomDialog bottomDialog = new SheetBottomDialog();
        bottomDialog.showNow(getSupportFragmentManager(),"normal");
        bottomDialog.setEventCallback(new IPhotoOptionCallback() {
            @Override
            public void onCamera() {
                /*gotoCamera();*/
                ToastUtils.showShort("后续开通更换头像功能哦~");
            }

            @Override
            public void onAlbum() {
                /*gotoAlbum();*/
                ToastUtils.showShort("后续开通更换头像功能哦~");
            }

            @Override
            public void onCancel() {
                /*ToastUtils.showShort("onCancel");*/
            }
        });
    }

    /* 跳转拍照 */
    private void gotoCamera() {
        PermissionUtils.permission(PermissionConstants.CAMERA, PermissionConstants.STORAGE)
                .callback(new PermissionUtils.SimpleCallback() {
                    @Override
                    public void onGranted() {
                        //系统常量， 启动相机的关键
                        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        /*picPath = FileUtils.createNewFilePath();
                        LogUtils.e("picPath:" + picPath);
                        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileUtils.createUriFromPath(picPath));*/
                        // 参数常量为自定义的request code, 在取返回结果时有用
                        startActivityForResult(openCameraIntent, Values.REQUEST_SYSTEM_CAMERA);
                    }

                    @Override
                    public void onDenied() {
                        ToastUtils.showShort(UIUtils.getString(R.string.refused_camera_permission_error));
                    }
                }).request();
    }

    /* 跳转相册 */
    private void gotoAlbum() {
        PermissionUtils.permission(PermissionConstants.CAMERA, PermissionConstants.STORAGE)
                .callback(new PermissionUtils.SimpleCallback() {
                    @Override
                    public void onGranted() {
                        Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
                        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                        startActivityForResult(albumIntent, Values.REQUEST_SYSTEM_ALBUM);
                    }

                    @Override
                    public void onDenied() {
                        ToastUtils.showShort(UIUtils.getString(R.string.refused_album_permission_error));
                    }
                }).request();
    }

    /* 昵称 */
    @OnClick(R.id.nick_ll)
    void onNickLlClicked(){
        IntentUtils.startActivityForResult(this,UpdateNicknameActivity.class,Values.REQUEST_CODE_1);
    }

    /* 性别 */
    @OnClick(R.id.gender_ll)
    void onGenderLlClicked(){
        new GenderBottomDialog().showNow2(getSupportFragmentManager(),"normal").gender(gender).setEventCallback(new IEventIndexCallback() {
            @Override
            public void onCancel() {

            }

            @Override
            public void onComfirm(int index) {
                udpateInfoWithGender(index);
            }
        });
    }

    /* 修改用户信息 */
    private void udpateInfoWithGender(int index){
        UpdateInfoVO updateInfoVO = new UpdateInfoVO();
        updateInfoVO.setGender(index);
        NetUtils.updateInfo(updateInfoVO, new MyObserver<MemberInfo>(this) {

            @Override
            public void onSuccess(MemberInfo result) {
                //更新用户信息保存本地
                SharedPreferencesUtil.putData(Keys.USER_INFO_MEMBER_KEY,result);
                Integer gender2 = result.getGender();
                if (null == gender2){
                    genderTv.setText("未填写");
                    gender = 0;
                } else {
                    String genderStr = (gender2 == 1 ? "男" : "女");
                    genderTv.setText(genderStr);
                    gender = gender2;
                }
                //提示
                ToastUtils.showShort("修改成功!");
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                LoadingUtils.hide();
                ToastUtils.showShort(errorMsg);
            }
        });
    }

    /* 修改密码 */
    @OnClick(R.id.update_pwd_ll)
    void onUpdatePwdLlClicked(){
        IntentUtils.startActivity(this,ResetPwdActivity.class);
    }

    @OnClick(R.id.done_btn)
    void onDoneBtnClicked(){
        /* 弹窗提示 */
        new NormalCenterDialog().showNow2(getSupportFragmentManager(),"normal").title("确定退出登录吗？").setEventCallback(new IEventCallback() {
            @Override
            public void onCancel() {

            }

            @Override
            public void onComfirm() {
                quitWithData();
            }
        });
    }

    /* 退出登录 */
    private void quitWithData(){
        doneBtn.setEnabled(false);
        LoadingUtils.show(this);
        NetUtils.logout(new MyObserver<String>(this) {
            @Override
            public void onSuccess(String result) {
                doneBtn.setEnabled(true);
                LoadingUtils.hide();
                //删除token
                NetUtils.removeToken();
                //从本地删除用户信息
                SharedPreferencesUtil.putData(Keys.TOKEN_KEY,"");
                SharedPreferencesUtil.putData(Keys.USER_INFO_MEMBER_KEY,new MemberInfo());

                //提示并退出
                ToastUtils.showShort("退出成功!");
                ActivityStackUtil.finishAllActivity();
                IntentUtils.startActivity(UserInfoActivity.this,SignInActivity.class);
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                doneBtn.setEnabled(true);
                LoadingUtils.hide();
                //提示
                ToastUtils.showShort(errorMsg);
            }
        });
    }

    /* 上传图片 */
    private void uploadImageData(){
        OSSPolicyResult result = (OSSPolicyResult)SharedPreferencesUtil.getData(Keys.OSS_TOKEN_KEY,new OSSPolicyResult());
        Logger.i("result->",result);
        String objName = "hehe.jpg";
        if (!TextUtils.isEmpty(result.getAccessKeyId())) {
            OSSNetUtils.getInstance().asyncUploadFile(objName, new ICallBack() {
                @Override
                public void onSuccess(Object data) {
                    ToastUtils.showShort(data.toString());
                }

                @Override
                public void onFailed(String error) {
                    ToastUtils.showShort(error);
                }
            });
        }
    }

    /* 上传成功回调 */
    private void aliyunOssCallback(){
        NetUtils.aliyunOssCallback(new MyObserver<OSSCallbackResult>(this) {
            @Override
            public void onSuccess(OSSCallbackResult result) {

            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                ToastUtils.showShort(errorMsg);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && data != null){
            switch (requestCode) {
                case Values.REQUEST_CODE_1:
                    String nickname = data.getStringExtra(Keys.NICKNAME_KEY);
                    if (TextUtils.isEmpty(nickname)) return;
                    nickTv.setText(nickname);
                    break;
                case Values.REQUEST_SYSTEM_CAMERA:

                    break;
                case Values.REQUEST_SYSTEM_ALBUM:
                    uploadImageData();
                    break;
                default:
                    break;
            }
        }
    }
}
